from django.core.management.base import BaseCommand

from gis.common import track_logging
from gis.common.telegram import send_text_msg_tele
from itpay.core.agency import agency_service
from itpay.core.conf import conf_client

_LOGGER = track_logging.getLogger(__name__)

WARNING_BALANCE = 10000000


class Command(BaseCommand):
    def handle(self, *args, **options):
        _LOGGER.info("begin check agency balance")
        try:
            for agency in agency_service.get_agencys_by_ids(get_check_agency_ids()):
                if agency["balance"] < WARNING_BALANCE:
                    send_text_msg_tele(
                        conf_client.get_value("telegram_group_id"),
                        "{}【{}】当前余额不足10000，请及时充值！".format(
                            agency["nickname"], agency["id"]
                        ),
                    )

        except Exception:
            _LOGGER.exception("fail check agency balance")
        _LOGGER.info("end check agency balance")


def get_check_agency_ids():
    return conf_client.get_dict("our_agency_ids")
